<?php

namespace src;

use src\interfaces\IUploadFile;

class UploadFile implements IUploadFile
{
    protected $file;
    protected $moved = false;

    public function __construct($file)
    {
        $this->file = $file;
    }

    public function getStream()
    {
        return $this->file ? stream_get_contents(fopen($this->file['tmp_name'], 'r')) : "";
    }

    public function moveTo($path, $newName = '')
    {
        if ($this->moved) {
            throw new \RuntimeException('File was moved to other directory');
        }
        $name = $this->file['name'];
        if (!empty($newName)){
            $newName .= strrchr($name,'.');
        }else{
            $newName = $name;
        }
        $target = $path."/".$newName;
        if(!move_uploaded_file($this->file['tmp_name'], $target)){
            throw new \RuntimeException('Unable to move upload file');
        }
        $this->moved = true;
        return $target;
    }

    public function getSize()
    {
        return $this->file['size'];
    }

    public function getFileType()
    {
        return $this->file['type'];
    }
}